<template>
  <div class="app-container">
    <!-- 订单详情 -->
    <div class="orderDetail">
      <h3>订单详情</h3>
      <el-descriptions
        class="margin-top"
        :column="2"
        :size="size"
        border
        :contentStyle="CS"
        :label-style="LS"
      >
        <el-descriptions-item>
          <template slot="label"> 订单名称 </template>
          {{ orderDetail.order_name }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 订单id </template>
          {{ orderDetail.order_id }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 归属品牌 </template>
          {{ orderDetail.brand_name }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 订单创建人 </template>
          {{ orderDetail.create_username }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 订单详情 </template>
          {{ orderDetail.order_details }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 订单备注 </template>
          {{ orderDetail.remarks }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 总成本 </template>
          {{ totalWorkAmount + totalCostAmount }} 元
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="orderDetail" v-if="orderDetail.chuanyun_object_id">
      <h3>氚云属性</h3>
      <el-descriptions
        class="margin-top"
        :column="2"
        :size="size"
        border
        :contentStyle="CS"
        :label-style="LS"
      >
        <el-descriptions-item>
          <template slot="label"> 记录ID </template>
          {{ orderDetail.chuanyun_object_id }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 订单编号 </template>
          {{ orderDetail.order_id }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 拥有者 </template>
          {{ orderDetail.chuanyun_owner_name }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 主PM </template>
          {{ orderDetail.chuanyun_pm_name }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 启动日期 </template>
          {{ orderDetail.chuanyun_start_time }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 完结日期 </template>
          {{ orderDetail.chuanyun_end_time }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <h3>项目工时成本：{{ totalWorkAmount }} 元</h3>
    <el-table
      v-loading="listLoading"
      :data="workingList"
      border
      fit
      highlight-current-row
      style="width: 100%"
      max-height="600"
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column prop="projects_name" label="项目ID" align="center">
      </el-table-column>
      <el-table-column prop="projects_name" label="项目名称" align="center">
      </el-table-column>
      <el-table-column prop="total_amount" label="项目总成本/元" align="center">
      </el-table-column>
    </el-table>
    <h3>其他成本：{{ totalCostAmount }} 元</h3>
    <div style="margin-bottom: 12px">
      <el-button
        icon="el-icon-plus"
        type="primary"
        size="mini"
        @click="handleAddCost"
      >
        添加成本
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="costLists"
      border
      fit
      highlight-current-row
      style="width: 100%"
      max-height="600"
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column prop="cost_name" label="名称" align="center">
      </el-table-column>
      <el-table-column prop="cost_amount" label="金额/元" align="center">
      </el-table-column>
      <el-table-column prop="cost_remark" label="备注" align="center">
      </el-table-column>
      <el-table-column label="创建时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.created_at">{{ row.created_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.updated_at">{{ row.updated_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button
            v-if="row.cost_name !== '总计'"
            type="text"
            size="small"
            @click="handleModify(row)"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="costTitle"
      :visible.sync="dialogFormVisible"
      width="550px"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="成本名称" label-width="120px" prop="costName">
          <el-input
            v-model="form.costName"
            autocomplete="off"
            maxlength="50"
            placeholder="请输入成本名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="成本金额" label-width="120px" prop="costAmount">
          <el-input
            v-model="form.costAmount"
            autocomplete="off"
            placeholder="请输入成本金额"
            oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/[^0-9.]/g, '').replace(/^\./g, '').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');if(value<=0)value=null"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="120px" prop="costRemark">
          <el-input
            type="textarea"
            rows="5"
            resize="none"
            maxlength="200"
            placeholder="请输入备注"
            v-model="form.costRemark"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeCost">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { curentTime } from "@/filters/index";
import {
  getOrdersDetailsById,
  getOrderCostLists,
  createOrderCostInfo,
  updateOrderCostInfo,
  delOrderCostInfo,
} from "@/api/order";

import { setWorkAmount } from "@/api/workingHours";
export default {
  name: "Details",
  filters: {
    formate(date) {
      return curentTime(date);
    },
  },
  data() {
    return {
      // 表单校验
      rules: {
        costName: [
          { required: true, message: "请输入成本名称", trigger: "blur" },
        ],
        costAmount: [
          { required: true, message: "请输入成本金额", trigger: "blur" },
        ],
        costRemark: [
          { required: false, message: "请输入成本备注", trigger: "blur" },
        ],
      },
      size: "",
      // 加载
      listLoading: true,
      // 订单id
      orderId: "",
      // 订单信息
      orderDetail: {},
      // 订单信息
      orderName: "",
      // 工时记录
      workingList: [],
      //  成本列表
      costLists: [],
      CS: {
        "min-width": "600px", //最小宽度
        "word-break": "break-all", //过长时自动换行
      },
      LS: {
        color: "#000",
        "font-weight": "600",
        "min-width": "110px",
        "word-break": "keep-all",
      },
      costTitle: "",
      dialogFormVisible: false,
      form: {
        costName: "",
        costAmount: 0,
        costRemark: "",
      },
      costId: null,
      totalCostAmount: 0, //  其他成本总计
      totalWorkAmount: 0, //  工时成本总计
    };
  },
  mounted() {
    if (this.$route.query && this.$route.query.id) {
      this.orderId = this.$route.query.id;
      this.getOrderDetails();
      this.getOrderCostLists();
    }
  },
  methods: {
    // 获取订单详细信息
    async getOrderDetails() {
      const res = await getOrdersDetailsById({ id: this.orderId })
      this.orderDetail = res.data.orderDetails || {};
      this.workingList = res.data.workingLists || [];
      this.listLoading = false;
      this.totalWorkAmount = 0;
      this.workingList.forEach(element => {
        this.totalWorkAmount += element.total_amount ? parseFloat(element.total_amount) : 0;
      });

      
    },
    //  新增成本
    handleAddCost() {
      this.costTitle = "新增成本";
      this.form.costName = "";
      this.form.costAmount = 0;
      this.form.costRemark = "";
      this.costId = null;
      this.dialogFormVisible = true;
    },
    // 修改订单
    handleModify(row) {
      this.costTitle = "编辑成本";
      this.form.costName = row.cost_name;
      this.form.costAmount = row.cost_amount;
      this.form.costRemark = row.cost_remark;
      this.orderId = row.order_id;
      this.costId = row.id;
      this.dialogFormVisible = true;
    },
    closeCost() {
      this.costTitle = "";
      this.form.costName = "";
      this.form.costAmount = 0;
      this.form.costRemark = "";
      this.costId = null;
      this.dialogFormVisible = false;
    },
    // 新增表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.costTitle === "新增成本") {
            createOrderCostInfo({
              cost_name: this.form.costName,
              cost_amount: this.form.costAmount,
              cost_remark: this.form.costRemark,
              order_id: this.orderId,
            }).then((res) => {
              if (res && res.success) {
                this.$message({
                  message: "新增成功",
                  type: "success",
                });
                this.getOrderCostLists();
                this.closeCost();
              } else {
                this.$message({
                  message: "新增失败",
                  type: "fail",
                });
              }
            });
          } else {
            updateOrderCostInfo({
              id: this.costId,
              cost_name: this.form.costName,
              cost_amount: this.form.costAmount,
              cost_remark: this.form.costRemark,
            }).then((res) => {
              if (res && res.success) {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                this.getOrderCostLists();
                this.closeCost();
              } else {
                this.$message({
                  message: "修改失败",
                  type: "fail",
                });
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    //  查询订单其他成本
    async getOrderCostLists() {
      const res = await getOrderCostLists({ id: this.orderId });
      console.log(res);
      if (res && res.success) {
        this.totalCostAmount = 0;
        for (let i = 0; i < res.data.length; i++) {
          const el = res.data[i];
          this.totalCostAmount += parseFloat(el.cost_amount);
        }
        // res.data.push({
        //   cost_name: "总计",
        //   cost_amount: this.totalCostAmount,
        // });
        this.costLists = res.data;
      }
    },
    //  为工时添加金额
    async handleSetWorkAmount(row) {
      let res = await setWorkAmount({
        id: row.id,
        union_id: row.union_id,
      });
      if (res && res.success) {
        this.getOrderDetails();
        this.$message({
          message: "获取成功",
          type: "success",
        });
      } else {
        this.$message({
          message: res.msg || "获取失败",
          type: "fail",
        });
      }
    },
    //表格合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index == 0) {
          sums[index] = "总计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (column.property === "cost_amount" || column.property === "total_amount") {
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else {
            sums[index] = "";
          }
        }
      });
      return sums;
    },
  },
};
</script>

<style lang="scss" scoped>
.orderDetail {
  margin-bottom: 20px;
}
</style>